import { message } from 'antd';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import {
  listDictValue,
  addDictValue,
  updateDictValue,
  removeDictValue,
} from '@/services/system/dictValue';
import type { DictItem, DictValueItem } from '@/services/system/types';
import { DictValueColumns } from './columns';

/**
 * 添加字典项
 *
 * @param fields
 */
const handleAdd = async (fields: DictValueItem) => {
  const hide = message.loading('正在新增字典项');

  try {
    await addDictValue({ ...fields, id: undefined });
    hide();
    message.success('字典项添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('字典项添加失败，请重试！');
    return false;
  }
};

/**
 * 更新字典项
 *
 * @param fields
 */
const handleUpdate = async (fields: DictValueItem, currentRow?: DictValueItem) => {
  const hide = message.loading('正在更新字典项');

  try {
    await updateDictValue({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('字典项更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('字典项更新失败，请重试');
    return false;
  }
};

/**
 * 删除字典项
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: DictValueItem[]) => {
  const hide = message.loading('正在删除字典项');
  if (!selectedRows) return true;

  try {
    await removeDictValue(selectedRows.map((row) => row.id));
    hide();
    message.success('字典项删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('字典项删除失败，请重试');
    return false;
  }
};

type DictValueProps = {
  dict: DictItem;
};

const DictValue: React.FC<DictValueProps> = (props) => {
  /** 新建窗口的弹窗 */
  const actionRef = useRef<ActionType>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  /** 国际化配置 */

  const columns: ProColumns<DictValueItem>[] = [
    ...DictValueColumns,
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id || 0);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            handleRemove([record]);
            actionRef.current?.reloadAndRest?.();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <>
      <EditableProTable<DictValueItem>
        actionRef={actionRef}
        rowKey="id"
        params={{ dictCode: props.dict?.code }}
        request={listDictValue}
        columns={columns}
        bordered
        cardProps={{
          bodyStyle: {
            padding: '0',
          },
        }}
        recordCreatorProps={{
          record: (index: number) => {
            return {
              id: '-' + index + '',
              dictCode: props.dict.code,
            };
          },
          type: 'primary',
        }}
        editable={{
          editableKeys,
          onChange: setEditableRowKeys,
          onSave: async (rowKey, data) => {
            if ((data?.id + '').startsWith('-')) {
              await handleAdd(data);
            } else {
              await handleUpdate(data);
            }
            actionRef.current?.reloadAndRest?.();
          },
        }}
      />
    </>
  );
};

export default DictValue;
